/*
 * @Description:
 * @Version: 2.0
 * @Autor: zhangjx
 * @Date: 2023-03-23 11:13:00
 * @LastEditors: zhangjx
 * @LastEditTime: 2023-05-29 18:55:49
 */
import { ElTree } from 'element-plus'
import type Node from 'element-plus/es/components/tree/src/model/node'
import apiMod from '@/apiMod/index'

interface Tree {
	name: string
	leaf?: boolean
}

export default defineComponent({
	name: 'AplidTree',
	props: {
		treeProps: {
			type: Object,
			default: {
				label: 'name',
				children: 'children',
				isLeaf: 'leaf',
			},
		},
		api: {
			type: String,
			default: 'adminAuthList',
		},
		parentId: {
			type: [String, Number],
			default: '0',
		},
		defaultCheckedKeys: {
			type: Array,
			default: () => [],
		},
		defaultExpandedKeys: {
			type: Array,
			default: () => [],
		},
		nodeKey: {
			type: [String, Number],
			default: 'id',
		},
		paramsObj: {
			type: Object,
			default: () => ({}),
		},
	},
	emits: ['update:node-click', 'update:check-change'],
	setup(props, { slots, attrs, emit, expose }) {
		const treeRef = ref<InstanceType<typeof ElTree>>()
		let selectNode = {}
		const setCheckedKeys = (treeCheckedKey) => {
			treeRef.value!.setCheckedKeys(treeCheckedKey, false)
		}

		const handleNodeClick = (node) => {
			emit('update:node-click', node)
		}

		const onCheckChange = (node, icChecked) => {
			selectNode[node[props.nodeKey]] = icChecked ? node : ''
			emit('update:check-change', selectNode, icChecked, node)
		}

		const loadData = async (node, leaf) => {
			const parent_no = node.level === 0 ? props.parentId : node.data[props.nodeKey]
			return await apiMod[props.api]({
				parent_no: parent_no,
				...props.paramsObj,
			}).then((res) => {
				const data = Array.isArray(res.data) ? res.data : res.records
				return data.map((item) => {
					return {
						...item,
						leaf,
					}
				})
			})
		}
		const loadNode = async (node?: Node, resolve?: (data: Tree[]) => void) => {
			const data = await loadData(node, false)
			resolve(data)
		}
		let treeData = ref([])
		onMounted(async () => {
			// setCheckedKeys()
			const { data } = await apiMod[props.api]({ ...props.paramsObj })
			treeData.value = data
		})
		expose({ setCheckedKeys })
		return () => {
			return (
				<el-tree
					ref="treeRef"
					data={treeData.value}
					props={props.treeProps}
					node-key={props.nodeKey}
					load={loadNode}
					lazy
					highlight-current
					show-checkbox
					default-expanded-keys={props.defaultExpandedKeys}
					default-checked-keys={props.defaultCheckedKeys}
					onNodeClick={handleNodeClick}
					onCheckChange={onCheckChange}
				/>
			)
		}
	},
})
